<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Brython Snake</title>
    <script type="text/javascript" src="./brython.min.js"></script>
    <script type="text/javascript" src="./brython_stdlib.js"></script>
    <style>
        body {
            background-color: #444;
            color: aliceblue;
        }

        canvas {
            margin-top: 1%;
            padding-left: 0;
            padding-right: 0;
            margin-left: auto;
            margin-right: auto;
            display: block;
            border: 1px solid #535353;
        }

        .score {
            color: red;
            font-size: 20px;
            text-align: center;
        }

        .section {
            text-align: center;
        }

        .text-center {
            text-align: center;
        }
    </style>

</head>

<body onload="brython()" style="margin: 0 auto">
<div class="section">brython <a href="https://github.com/brython-dev/brython">Python!</a></div>
<div>
    <div id="score" class="score">得分: 0</div>
    <div id="high-score" class="score">最高分: 0</div>
    <div id="delayTime" class="score">速度: 0</div>
</div>

<canvas id="game-board" width="620" height="620"></canvas>
<div class="text-center">
    <button id="instructions-btn" class="btn btn-info">操作提示</button>
</div>



<script type="text/python">
    from browser import document, html, window
    import random

    # 定义一个类来管理游戏相关状态和操作，避免过多全局变量
    class SnakeGame:
        def __init__(self):
            self.score = 0
            self.high_score = 0
            self.px = 10
            self.py = 10
            self.grid_size = 25
            self.total_cells = 25
            self.ax = 15
            self.ay = 15
            self.xv = 0
            self.yv = 0
            self.trail = []
            self.tail = 5
            self.pre_pause = [0, 0]
            self.paused = False
            self.delayTime = 300
            self.canvas = document["game-board"]
            self.ctx = self.canvas.getContext("2d")
            document.addEventListener("keydown", self.key_push)
            self.game_loop = window.setInterval(self.game, self.delayTime)
            instructions_btn = document["instructions-btn"]
            instructions_btn.addEventListener("click", self.show_instructions)

        def game(self):
            self.px += self.xv
            self.py += self.yv
            if self.px < 0:
                self.px = self.total_cells - 1
            if self.px > self.total_cells - 1:
                self.px = 0
            if self.py < 0:
                self.py = self.total_cells - 1
            if self.py > self.total_cells - 1:
                self.py = 0
            self.ctx.fillStyle = "wheat"
            self.ctx.fillRect(0, 0, self.canvas.width, self.canvas.height)
            self.ctx.fillStyle = "lime"
            for i in range(len(self.trail)):
                self.ctx.fillRect(self.trail[i][0] * self.grid_size, self.trail[i][1] * self.grid_size,
                                  self.grid_size - 2, self.grid_size - 2)
                if self.trail[i][0] == self.px and self.trail[i][1] == self.py:
                    self.delayTime = 300
                    self.score = self.score if self.paused else 0
                    self.tail = self.tail if self.paused else 5
                    self.update_ui()
            self.trail.insert(0, [self.px, self.py])
            while len(self.trail) > self.tail:
                self.trail.pop()

            if self.ax == self.px and self.ay == self.py:
                self.tail += 1
                self.ax = int(random.random() * self.total_cells)
                self.ay = int(random.random() * self.total_cells)
                self.score += 1
                self.update_score(self.score)
            self.ctx.fillStyle = "red"
            self.ctx.fillRect(self.ax * self.grid_size, self.ay * self.grid_size, self.grid_size - 2,
                              self.grid_size - 2)

        def update_score(self, new_score):
            self.score = new_score
            if new_score > self.high_score:
                self.high_score = new_score
            # 使用字典简化速度设置逻辑
            delay_time_mapping = {
                0: 300,
                20: 250,
                50: 200,
                100: 150,
                200: 100
            }
            for max_score, time in delay_time_mapping.items():
                if new_score <= max_score:
                    self.delayTime = time
                    break
            else:
                self.delayTime = 50
            window.clearInterval(self.game_loop)
            self.game_loop = window.setInterval(self.game, self.delayTime)
            self.update_ui()

        def key_push(self, evt):
            key = evt.keyCode
            if key == 37 and not self.paused:
                self.xv = -1
                self.yv = 0
            elif key == 38 and not self.paused:
                self.xv = 0
                self.yv = -1
            elif key == 39 and not self.paused:
                self.xv = 1
                self.yv = 0
            elif key == 40 and not self.paused:
                self.xv = 0
                self.yv = 1
            elif key == 32:
                temp = [self.xv, self.yv]
                self.xv = self.pre_pause[0]
                self.yv = self.pre_pause[1]
                self.pre_pause = [*temp]
                self.paused = not self.paused

        def show_instructions(self, evt):
            window.alert("使用箭头键移动，按空格键暂停游戏。")

        def update_ui(self):
            document["score"].innerHTML = f"得分: {self.score}"
            document["high-score"].innerHTML = f"最高分: {self.high_score}"
            document["delayTime"].innerHTML = f"速度: {self.delayTime}"

    game = SnakeGame()

</script>

</body>

</html>